<template>
  <div class="backend-integration-test">
    <h2>后端集成测试</h2>
    
    <el-card class="test-card">
      <template #header>
        <h3>1. 当前医生信息</h3>
      </template>
      
      <div class="info-section">
        <p><strong>医生ID:</strong> {{ doctorInfo.id || '未获取' }}</p>
        <p><strong>用户名:</strong> {{ doctorInfo.username || '未获取' }}</p>
        <p><strong>真实姓名:</strong> {{ doctorInfo.realName || '未获取' }}</p>
        <p><strong>当前头像路径:</strong> {{ doctorInfo.avatar || '无' }}</p>
        <p><strong>计算后的头像URL:</strong> {{ computedAvatarUrl }}</p>
      </div>
      
      <div class="avatar-display">
        <h4>头像显示测试</h4>
        <el-avatar 
          :src="computedAvatarUrl" 
          :size="100"
          @error="onAvatarError"
          @load="onAvatarLoad"
        />
        <p v-if="avatarLoadStatus" :class="avatarLoadStatus.type">
          {{ avatarLoadStatus.message }}
        </p>
      </div>
    </el-card>
    
    <el-card class="test-card">
      <template #header>
        <h3>2. API接口测试</h3>
      </template>
      
      <div class="api-test-section">
        <el-button @click="testGetDoctorInfo" :loading="testing.getDoctorInfo">
          测试获取医生信息
        </el-button>
        
        <el-button @click="testGetCurrentDoctorAvatar" :loading="testing.getAvatar">
          测试获取当前医生头像
        </el-button>
        
        <el-button @click="testGetDoctorAvatar" :loading="testing.getDoctorAvatar">
          测试获取指定医生头像
        </el-button>
      </div>
      
      <div v-if="apiResults.length > 0" class="api-results">
        <h4>API测试结果:</h4>
        <div v-for="(result, index) in apiResults" :key="index" class="api-result">
          <p><strong>{{ result.api }}:</strong></p>
          <pre>{{ JSON.stringify(result.data, null, 2) }}</pre>
        </div>
      </div>
    </el-card>
    
    <el-card class="test-card">
      <template #header>
        <h3>3. 文件上传测试</h3>
      </template>
      
      <div class="upload-test-section">
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleFileChange"
          accept="image/*"
          class="upload-test"
        >
          <el-button type="primary">选择测试图片</el-button>
        </el-upload>
        
        <div v-if="selectedFile" class="file-info">
          <h4>选择的文件:</h4>
          <p><strong>文件名:</strong> {{ selectedFile.name }}</p>
          <p><strong>文件大小:</strong> {{ formatFileSize(selectedFile.size) }}</p>
          <p><strong>文件类型:</strong> {{ selectedFile.type }}</p>
          
          <div class="file-preview">
            <img v-if="filePreview" :src="filePreview" alt="预览" style="max-width: 200px; max-height: 200px;" />
          </div>
          
          <div class="upload-actions">
            <el-button type="success" @click="testUpload" :loading="testing.upload">
              测试上传
            </el-button>
            <el-button @click="clearFile">清除文件</el-button>
          </div>
        </div>
      </div>
      
      <div v-if="uploadResult" class="upload-result">
        <h4>上传结果:</h4>
        <pre>{{ JSON.stringify(uploadResult, null, 2) }}</pre>
      </div>
    </el-card>
    
    <el-card class="test-card">
      <template #header>
        <h3>4. URL处理测试</h3>
      </template>
      
      <div class="url-test-section">
        <el-input
          v-model="testUrl"
          placeholder="输入要测试的URL或文件路径"
          style="margin-bottom: 10px;"
        />
        
        <el-button @click="testUrlProcessing">测试URL处理</el-button>
        
        <div v-if="urlTestResult" class="url-test-result">
          <h4>URL处理结果:</h4>
          <p><strong>输入:</strong> {{ testUrl }}</p>
          <p><strong>处理后:</strong> {{ urlTestResult }}</p>
          <img v-if="urlTestResult" :src="urlTestResult" alt="测试图片" style="max-width: 200px; max-height: 200px;" />
        </div>
      </div>
    </el-card>
    
    <el-card class="test-card">
      <template #header>
        <h3>5. 错误处理测试</h3>
      </template>
      
      <div class="error-test-section">
        <el-button @click="testInvalidAvatar">测试无效头像</el-button>
        <el-button @click="testNetworkError">测试网络错误</el-button>
        <el-button @click="testLargeFile">测试大文件</el-button>
        
        <div v-if="errorTestResult" class="error-test-result">
          <h4>错误测试结果:</h4>
          <p :class="errorTestResult.type">{{ errorTestResult.message }}</p>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getDoctorInfo, getCurrentDoctorAvatar, getDoctorAvatar } from '../api/doctor'
import { uploadAvatar } from '../api/upload'
import { getAvatarUrl, validateAvatarFile, createAvatarPreview, base64ToFile } from '../utils/avatarUtils'

// 响应式数据
const doctorInfo = ref({})
const avatarLoadStatus = ref(null)
const apiResults = ref([])
const testing = ref({
  getDoctorInfo: false,
  getAvatar: false,
  getDoctorAvatar: false,
  upload: false
})

const selectedFile = ref(null)
const filePreview = ref('')
const uploadResult = ref(null)
const uploadRef = ref()

const testUrl = ref('')
const urlTestResult = ref('')
const errorTestResult = ref('')

// 计算属性
const computedAvatarUrl = computed(() => {
  return getAvatarUrl(doctorInfo.value)
})

// 头像加载事件
const onAvatarLoad = (event) => {
  avatarLoadStatus.value = {
    type: 'success',
    message: '头像加载成功: ' + event.target.src
  }
  ElMessage.success('头像加载成功')
}

const onAvatarError = (event) => {
  avatarLoadStatus.value = {
    type: 'error',
    message: '头像加载失败: ' + event.target.src
  }
  ElMessage.error('头像加载失败')
  
  // 设置默认头像
  if (event.target && event.target.src !== '/default-avatar.png') {
    event.target.src = '/default-avatar.png'
  }
}

// API测试函数
const testGetDoctorInfo = async () => {
  testing.value.getDoctorInfo = true
  try {
    const response = await getDoctorInfo()
    apiResults.value.push({
      api: 'getDoctorInfo',
      data: response
    })
    ElMessage.success('获取医生信息成功')
  } catch (error) {
    apiResults.value.push({
      api: 'getDoctorInfo',
      data: { error: error.message }
    })
    ElMessage.error('获取医生信息失败: ' + error.message)
  } finally {
    testing.value.getDoctorInfo = false
  }
}

const testGetCurrentDoctorAvatar = async () => {
  testing.value.getAvatar = true
  try {
    const response = await getCurrentDoctorAvatar()
    apiResults.value.push({
      api: 'getCurrentDoctorAvatar',
      data: response
    })
    ElMessage.success('获取当前医生头像成功')
  } catch (error) {
    apiResults.value.push({
      api: 'getCurrentDoctorAvatar',
      data: { error: error.message }
    })
    ElMessage.error('获取当前医生头像失败: ' + error.message)
  } finally {
    testing.value.getAvatar = false
  }
}

const testGetDoctorAvatar = async () => {
  testing.value.getDoctorAvatar = true
  try {
    const response = await getDoctorAvatar(doctorInfo.value.id)
    apiResults.value.push({
      api: 'getDoctorAvatar',
      data: response
    })
    ElMessage.success('获取指定医生头像成功')
  } catch (error) {
    apiResults.value.push({
      api: 'getDoctorAvatar',
      data: { error: error.message }
    })
    ElMessage.error('获取指定医生头像失败: ' + error.message)
  } finally {
    testing.value.getDoctorAvatar = false
  }
}

// 文件处理函数
const handleFileChange = (file) => {
  selectedFile.value = file.raw
  
  // 验证文件
  const validation = validateAvatarFile(file.raw)
  if (!validation.valid) {
    ElMessage.error(validation.message)
    return
  }
  
  // 创建预览
  createAvatarPreview(file.raw, (url) => {
    filePreview.value = url
  })
}

const testUpload = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择文件')
    return
  }
  
  testing.value.upload = true
  try {
    const response = await uploadAvatar(selectedFile.value)
    uploadResult.value = response
    ElMessage.success('文件上传成功')
  } catch (error) {
    uploadResult.value = { error: error.message }
    ElMessage.error('文件上传失败: ' + error.message)
  } finally {
    testing.value.upload = false
  }
}

const clearFile = () => {
  selectedFile.value = null
  filePreview.value = ''
  uploadResult.value = null
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// URL处理测试
const testUrlProcessing = () => {
  if (!testUrl.value) {
    ElMessage.warning('请输入要测试的URL')
    return
  }
  
  urlTestResult.value = getAvatarUrl(testUrl.value)
  ElMessage.success('URL处理完成')
}

// 错误处理测试
const testInvalidAvatar = () => {
  const invalidUrl = 'invalid/path/to/avatar.jpg'
  const result = getAvatarUrl(invalidUrl)
  errorTestResult.value = {
    type: 'info',
    message: `测试无效头像URL: ${invalidUrl} -> ${result}`
  }
}

const testNetworkError = async () => {
  try {
    await getDoctorAvatar(999999) // 不存在的医生ID
  } catch (error) {
    errorTestResult.value = {
      type: 'error',
      message: `网络错误测试: ${error.message}`
    }
  }
}

const testLargeFile = () => {
  // 创建一个模拟的大文件
  const largeFile = new File([''], 'large.jpg', { type: 'image/jpeg' })
  Object.defineProperty(largeFile, 'size', { value: 10 * 1024 * 1024 }) // 10MB
  
  const validation = validateAvatarFile(largeFile)
  errorTestResult.value = {
    type: validation.valid ? 'success' : 'error',
    message: `大文件测试: ${validation.message}`
  }
}

// 工具函数
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 组件挂载时获取医生信息
onMounted(async () => {
  try {
    const response = await getDoctorInfo()
    if (response.code === 200) {
      doctorInfo.value = response.data
    }
  } catch (error) {
    console.error('获取医生信息失败:', error)
  }
})
</script>

<style scoped>
.backend-integration-test {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-card {
  margin-bottom: 20px;
}

.info-section p {
  margin: 5px 0;
}

.avatar-display {
  margin-top: 15px;
  text-align: center;
}

.success {
  color: #67c23a;
}

.error {
  color: #f56c6c;
}

.info {
  color: #909399;
}

.api-test-section {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.api-results {
  margin-top: 15px;
}

.api-result {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.api-result pre {
  margin: 5px 0;
  white-space: pre-wrap;
  word-break: break-all;
}

.upload-test-section {
  margin-bottom: 15px;
}

.file-info {
  margin-top: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.file-preview {
  margin: 10px 0;
  text-align: center;
}

.upload-actions {
  margin-top: 10px;
}

.upload-result {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.upload-result pre {
  margin: 5px 0;
  white-space: pre-wrap;
  word-break: break-all;
}

.url-test-section {
  margin-bottom: 15px;
}

.url-test-result {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  text-align: center;
}

.error-test-section {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.error-test-result {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>

